import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom'
import { ActionSheet, NavBar, Icon, List, InputItem, TextareaItem, Modal, Toast, SearchBar } from 'antd-mobile';
import { CancelOrder, ParentOrderDetails } from "@/api/order/order.js"
import buildSteps from "./common";
import { R, createInfoWindow } from "@/assets/js/dict.js"
import './orderDetails.scss';
import AMap from 'AMap';
import mark from "@/assets/svg/mark.svg";


const confirm = Modal.alert;

const Item = List.Item;
const Brief = Item.Brief;

const editable = 'false';

/*
* 订单的详情页，审核用的
* */
function OrderDetailsOfAudit (props) {
    let [OrderDetailsData, setOrderDetailsData] = useState({ students: [], student_ids: "" }); // 相当于 this.state
    let [order_id, setOrder_id] = useState(props.order_id);
    let [status, setStatus] = useState("");

    const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
    let wrapProps;
    if (isIPhone) {
        wrapProps = {
            onTouchStart: e => e.preventDefault(),
        };
    }


    let showActionSheet = () => {
        const BUTTONS = ['撤回订单', '关闭'];
        ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            destructiveButtonIndex: BUTTONS.length - 2,
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps,
        },
            (buttonIndex) => {
                switch (buttonIndex) {
                    case 0:
                        confirm('撤回订单', '确定要撤回订单吗', [
                            { text: '取消', onPress: () => console.log('cancel') },
                            {
                                text: '撤回', onPress: () => {
                                    cancel();
                                }
                            },
                        ]);
                        break;
                    case 1:
                        break;
                    default:
                        break;
                }
            });
    };

    /**
     * 撤回订单
     */
    function cancel () {
        CancelOrder({ order_id: order_id }, (res) => {
            if (res[R.code] === R.success) {
                Toast.success("操作成功");
                props.doFlush(new Date().getTime());
            } else {
                Toast.fail("操作异常：" + res[R.msg]);
            }
        });
    }

    function getOrderDetails () {
        let obj = props.OrderDetailsData;
        let order_id;
        if (!!obj) {
            order_id = obj.id;
        } else {
            order_id = sessionStorage.getItem("order_id");
        }
        ParentOrderDetails({ order_id: order_id }, (res) => {
            if (R.isSuccess(res)) {
                let data = R.getData(res);
                setStatus(data.status);
                setOrder_id(order_id);
                setOrderDetailsData(data);

                //展示地图
                if (null !== data.longitude && null !== data.latitude) {
                    let mapInstance = new AMap.Map('amap', {
                        resizeEnable: true,
                        zoomEnable: false,
                        dragEnable: true,
                        center: [data.longitude, data.latitude],//传入地址的经纬度
                        zoom: 13
                    });
                    mapInstance.on('complete', function () {
                        AMap.plugin(['AMap.Geocoder', 'AMap.Marker', 'AMap.LngLat', 'AMap.Pixel', 'AMap.Icon', 'AMap.OverlayGroup', 'AMap.Autocomplete'], () => {
                            let markPoint = new AMap.Marker({
                                position: new AMap.LngLat(data.longitude, data.latitude),
                                offset: new AMap.Pixel(-10, -10),
                                icon: mark, // 添加 Icon 图标 URL
                                title: '教学地址',
                                label: {
                                    // content: '<span style="color: darkgreen; font-size: x-large"><strong>选中的地址</strong></span>'
                                }
                            });

                            let geocoder = new AMap.Geocoder({
                                city: "", //城市设为北京，默认：“全国”
                                radius: 1000 //范围，默认：500
                            });

                            let address = ''; // 点击坐标的详细地址； 

                            geocoder.getAddress([data.longitude, data.latitude], (status, result) => {
                                if (status === 'complete' && result.regeocode) {
                                    address = result.regeocode.formattedAddress;

                                    //实例化信息窗体
                                    let title = '详细地址：',
                                        content = [];
                                    content.push(address);

                                    //构建自定义信息窗体
                                    let infoWindow = new AMap.InfoWindow({
                                        position: new AMap.LngLat(data.longitude, data.latitude),
                                        offset: new AMap.Pixel(24, -4),
                                        autoMove: true,
                                        isCustom: true,  //使用自定义窗体
                                        content: createInfoWindow(title, content.join("<br/>"), mapInstance),
                                    });

                                    infoWindow.open(mapInstance)
                                } else {
                                    console.error('根据经纬度查询地址失败')
                                }
                            });

                            //添加标识物
                            mapInstance.add(markPoint);
                        });
                    });
                }
            }
        });
    }

    useEffect(() => {
        getOrderDetails();
    }, []);


    function back () {
        props.history.goBack();
    }

    return (
        <div className="orderDetails">
            <div className="page-title  home-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    rightContent={[
                        <span key="1" onClick={showActionSheet}>操作</span>,
                    ]}
                    onLeftClick={back}
                >
                    提交审核的订单
                </NavBar>
            </div>

            <div className="page-content  home-content">
                <div className="publish-content-piece">
                    <div className="form-box">
                        <div className="form-con">
                            {buildSteps(status)}
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>
                                基本要求
                            </strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <InputItem
                                    type="text"
                                    editable={editable}
                                    value={OrderDetailsData.parent_name}
                                >家长姓名</InputItem>
                                <InputItem
                                    editable={editable}
                                    value={OrderDetailsData.parent_gender}

                                >家长性別</InputItem>
                                <List.Item
                                    extra={OrderDetailsData.class_fee ? "￥" + OrderDetailsData.class_fee / 100 : ''}
                                >课时费</List.Item>

                                <List.Item extra={OrderDetailsData.learn_hours}>可授课时间段</List.Item>
                                <List.Item
                                    extra={OrderDetailsData.subjects}
                                >
                                    辅导科目
                                </List.Item>

                            </List>

                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>
                                上课地址
                            </strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <InputItem
                                    editable={false}
                                    value={OrderDetailsData.learn_address}
                                >地址</InputItem>
                            </List>
                            <div id="amap" style={{ width: '100%', height: '300px' }} />
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>对家教老师的要求</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <TextareaItem
                                    editable={editable}
                                    value={OrderDetailsData.demand}
                                    rows="6"
                                    autoHeight
                                    rows={5}
                                />
                            </List>
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>学生</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                {OrderDetailsData.students.map((item, index) => {
                                    return (
                                        <Item key={index}
                                            arrow="empty"
                                            multipleLine
                                            onClick={() => {
                                                console.log("item-->", item);
                                            }}
                                            platform="cross"
                                        >
                                            名称：{item.name}
                                            <Brief> 年龄：{item.age}</Brief>
                                            <Brief> 年级：{item.grade}</Brief>
                                            <Brief> 说明：{item.note}</Brief>
                                        </Item>
                                    )
                                })}
                            </List>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default withRouter(OrderDetailsOfAudit);